package com.example.waimai.filter;

import com.alibaba.fastjson.JSON;
import com.example.waimai.common.BaseContext;
import com.example.waimai.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //匹配统配符
     public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override//添加拦截器，使得每次都必须先登录才能访问页面
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        //获取本次请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //判断本次是否需要处理
        boolean check = check(urls, requestURI);
        //如果不需要处理，直接放行
        if(check) {
            filterChain.doFilter(request, response);
            return;
        }
        //判断登录状态，if登录 放行
        if(request.getSession().getAttribute("employee")!=null){
            long employId = (long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employId);

            filterChain.doFilter(request,response);
            return;
        }
        //未登录，返回未登录的结果
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }
    public boolean check(String[] urls, String requestURI){
        for(String url:urls){
            boolean mtach=PATH_MATCHER.match(url,requestURI);
            if(mtach){
                return true;
            }
        }
        return false;
    }
}
